package com.leyou.cart.service.impl;

import com.leyou.cart.client.GoodsClient;
import com.leyou.cart.interceptor.LoginInterceptor;
import com.leyou.cart.pojo.Cart;
import com.leyou.cart.service.CartService;
import com.leyou.common.pojo.UserInfo;
import com.leyou.common.utils.JsonUtils;
import com.leyou.item.pojo.Sku;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Resource
    private GoodsClient goodsClient;

    private static final String KEY_PREFIX = "user:cart:";

    /**
     * 添加购物车
     * @param cart
     * @return
     */
    @Override
    public void addCart(Cart cart) {
        //获取用户信息
        UserInfo userInfo = LoginInterceptor.getUserInfo();

        //查询购物车记录
        BoundHashOperations<String, Object, Object> hashOperations = this.redisTemplate.boundHashOps(KEY_PREFIX + userInfo.getId());

        //把hash里的skuId转换未Spring类型
        String key = cart.getSkuId().toString();

        //记录用户传过来的购物车数量
        Integer cartNum = cart.getNum();

        //判断当前商品是否在购物车里
        Boolean hasKey = hashOperations.hasKey(key);



        if (hasKey){
            /**
             * 在，更新数量
             */
            //获取cart的JSON数据
            String cartJson = hashOperations.get(key).toString();

            //使用JsonUtils工具类序列化cartJson为Cart对象
             cart = JsonUtils.parse(cartJson, Cart.class);
             cart.setNum(cart.getNum()+cartNum);

             //更新到redis中
            hashOperations.put(key,JsonUtils.serialize(cart));
        }else {
            /**
             * 不在，添加购物车
             */
            /*
               设置购物车信息
             */
            //根据skuId查询sku
            Sku sku = this.goodsClient.querySkuBySkuId(cart.getSkuId());
                //设置用户id
                cart.setUserId(userInfo.getId());
                //设置购物车信息
                cart.setTitle(sku.getTitle());
                cart.setOwnSpec(sku.getOwnSpec());
                cart.setImage(StringUtils.isBlank(sku.getImages()) ? "" : StringUtils.split(sku.getImages(),",")[0]);
                cart.setPrice(sku.getPrice());
        }
        //新增购物车
        hashOperations.put(key,JsonUtils.serialize(cart));
    }

    /**
     * 查询购物车
     * @return
     */
    @Override
    public List<Cart> queryCart() {
        //获取用户信息
        UserInfo userInfo = LoginInterceptor.getUserInfo();

        //先去判断用户是否有购物车记录
        if (!this.redisTemplate.hasKey(KEY_PREFIX + userInfo.getId())){
            return null;
        }

        //获取用户信息下的购物车
        BoundHashOperations<String, Object, Object> hashOperations = this.redisTemplate.boundHashOps(KEY_PREFIX + userInfo.getId());

        //获取购物车集合
        List<Object> cartsJson = hashOperations.values();

        //判断用户是否有购物车集合
        if(CollectionUtils.isEmpty(cartsJson)){
            return null;
        }

        //把一个List<Object>集合转换为List<Cart>集合
        List<Cart> carts = cartsJson.stream().map(cartJson -> JsonUtils.parse(cartJson.toString(), Cart.class)).collect(Collectors.toList());
        return carts;
    }

    /**
     * 修改购物车数量
     * @param cart
     * @return
     */
    @Override
    public void updateCartNum(Cart cart) {
        //获取用户信息
        UserInfo userInfo = LoginInterceptor.getUserInfo();

        //先去判断用户是否有购物车记录
        if (!this.redisTemplate.hasKey(KEY_PREFIX + userInfo.getId())){
            return ;
        }

        //获取购物车数量
        Integer num = cart.getNum();

        //获取用户信息下的购物车
        BoundHashOperations<String, Object, Object> hashOperations = this.redisTemplate.boundHashOps(KEY_PREFIX + userInfo.getId());

        //获取购物车集合
        String cartJson = hashOperations.get(cart.getSkuId().toString()).toString();

        cart = JsonUtils.parse(cartJson,Cart.class);

        cart.setNum(num);

        hashOperations.put(cart.getSkuId().toString(),JsonUtils.serialize(cart));
    }

    /**
     * 删除购物车
     * @param skuId
     * @return
     */
    @Override
    public void deleteCart(String skuId) {
        //获取用户信息
        UserInfo userInfo = LoginInterceptor.getUserInfo();

        //把hash里的skuId转换未Spring类型
        String key = KEY_PREFIX+userInfo.getId();

        BoundHashOperations<String, Object, Object> hashOperations = this.redisTemplate.boundHashOps(key);

        hashOperations.delete(skuId);
    }
}
